/* ----------------------------------------------------------------------------
* File: message_queue_impl.cpp
*
* Desc: Message queue implementation
*
* Created: 29/05/2011, by Alexey Korshunov
* ---------------------------------------------------------------------------- */
#include "message_queue_impl.h"
#include "exception.h"


namespace ModuleManagement
{
	MessageQueueImpl::MessageQueueImpl()
		: m_top(NULL)
		, m_cur(NULL)
		, m_Count(0)
	{
		InitializeCriticalSection(&m_Access);
	}

	MessageQueueImpl::~MessageQueueImpl()
	{
		Clear();
		DeleteCriticalSection(&m_Access);
	}

	size_t MessageQueueImpl::GetCount() const
	{
		return m_Count;
	}

	void MessageQueueImpl::PutMsg(const Common::MsgInfo& info)
	{
		Node* node = new Node;
		node->data = info;

		EnterCriticalSection(&m_Access);
		if (m_top == NULL)
			m_top = node;
		else
			m_cur->next = node;
		m_cur = node;
		++m_Count;
		LeaveCriticalSection(&m_Access);
	}

	void MessageQueueImpl::GetMsg(Common::MsgInfo& info)
	{
		if (m_top != NULL)
		{
			EnterCriticalSection(&m_Access);

			info = m_top->data;
			Node* next = m_top->next;
			delete m_top;
			m_top = next;
			--m_Count;

			LeaveCriticalSection(&m_Access);
		}
	}

	void MessageQueueImpl::Clear()
	{
		EnterCriticalSection(&m_Access);

		while(m_top != NULL)
		{
			Node* next = m_top;
			m_top = m_top->next;
			delete next;
		}
		m_cur = NULL;

		LeaveCriticalSection(&m_Access);
	}
}